﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ZLDC.Common;
using System.IO.Compression;

namespace ZLDC.Estate
{
                public class HttpModule : System.Web.IHttpModule
    {

        #region IHttpModule 成员

                                public void Dispose()
        {
            throw new NotImplementedException();
        }

                                        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(BeginRequest);
        }

        #endregion

                                                public void BeginRequest(Object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;

            if (app.Context.CurrentHandler is System.Web.UI.Page && app.Request["HTTP_X_MICROSOFTAJAX"] == null)
            {
                if (IsEncodingAccepted(GZIP))
                {
                    app.Response.Filter = new GZipStream(app.Response.Filter, CompressionMode.Compress);
                    SetEncoding(GZIP);
                }
                else if (IsEncodingAccepted(DEFLATE))
                {
                    app.Response.Filter = new DeflateStream(app.Response.Filter, CompressionMode.Compress);
                    SetEncoding(DEFLATE);
                }
            }
        }

        private const string GZIP = "gzip";
        private const string DEFLATE = "deflate";

        private static bool IsEncodingAccepted(string encoding)
        {
            HttpContext context = HttpContext.Current;
            return context.Request.Headers["Accept-encoding"] != null && context.Request.Headers["Accept-encoding"].Contains(encoding);
        }

        private static void SetEncoding(string encoding)
        {
            HttpContext.Current.Response.AppendHeader("Content-encoding", encoding);
        } 

    }
}